import { Rule } from 'rule.js';
const msg = require('message.js');

class Validate {
	rules='';//规则
	isReturnErr = false;//是否返回错误，默认false

	constructor() {

	}

	/**
	 * 设置场景
	 */
	setScene(value){
		this.rules=this.getScene(value);
		return this;
	}
	/**
	 * 参数效验
	 * @param {*} params 对象，例：｛id:43,name:'raymond',age:15}
	 * scene 场景值,字符串
	 */
	goCheck(params) {
		if ((typeof params) != "object") {
			wx.showToast({
				title: '参数不是一个对象',
				icon: 'none', duration: 2000
			})
			throw "参数不是一个对象";
		}

		var errorMsg = '';
		for (let key in params) {
			// console.log(key + '---' + params[key])

			//判断参数中的字段是否存在，不存在则跳出当前循环
			if (this.rules[key] == undefined) {
				continue;
			};

			errorMsg = this.isRule(this.rules, key, params);
			if (errorMsg) {
				//报错后跳出循环
				break;
			}
		}
		return errorMsg;
	}
	/**
	 * 判断规则
	 */
	isRule(rules, key, params) {
		try {
			var rule = (rules[key]).split('|');
			rule.forEach((item, index) => {
				var errObj = { errorMsg: '' };
				var rule = new Rule();
				if (!rule[item](params[key])) {
					if (this.message[key + '.' + item] == undefined || this.message[key + '.' + item] == "") {
						//参数验证错误的信息
						errObj.errorMsg = msg.msg[item] + key;
						errObj[key] = msg.msg[item] + key;
						if (!this.isReturnErr) {
							wx.showToast({
								title: msg.msg[item] + key,
								icon: 'none', duration: 3000
							});
						}
						throw errObj
					} else {
						//参数验证错误的信息
						errObj.errorMsg = this.message[key + '.' + item];
						errObj[key] = this.message[key + '.' + item];
						if (!this.isReturnErr) {
							wx.showToast({
								title: this.message[key + '.' + item],
								icon: 'none', duration: 3000
							});
						}
						throw errObj
					}
				}
			});
		} catch (e) {
			if (this.isReturnErr) {
				return e;
			} else {
				throw e;
			}
		}
	}

	/**
	 * 获取数据验证的场景
	 */
	getScene(scene) {
		var sceneArr = this.scene[scene];
		if (sceneArr == undefined || sceneArr == "") {
			throw '场景不存在';
		}

		var sceneObj = {}
		//循环场景数组
		sceneArr.forEach((item, index) => {
			for (let key in this.rules) {
				if (item == key) {
					sceneObj[key] = this.rules[key];
				} else {
					continue;
				}
			}
		})
		return sceneObj;
	}
}

export { Validate };